package com.liao.badminton.code.util;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//@Component
public class MyFileUtil {
    private static int serverPort; //11080
    private static String prePath; ///badminton
    private static String filePath; //G:\\upload

    private static String mergePath = "mergeTemp/";

    private static String systemPath = System.getProperties().getProperty("file.separator");

    static {
        ServerProperties serverProperties = SpringUtil.getBean(ServerProperties.class);
        MultipartProperties multipartProperties = SpringUtil.getBean(MultipartProperties.class);
        MyFileUtil.serverPort = serverProperties.getPort();
        MyFileUtil.prePath = serverProperties.getServlet().getContextPath();
        MyFileUtil.filePath = multipartProperties.getLocation();
    }

    /**
     * 保存文件的路径：filePath+“/”+timeFormat
     * G:\\upload\2023-11-11\
     *
     * @return
     */
    public static String getBasePath() {
        String timeFormat = DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDateTime.now());
        String path = filePath + systemPath + timeFormat + systemPath;
        if (!cn.hutool.core.io.FileUtil.exist(path)) {
            new File(path).mkdirs();
        }
        return path;
    }

    /**
     * 分片上传临时文件
     *
     * @return
     */
    public static String getBasePathMerge() {
        String path = filePath + systemPath + mergePath;
        if (!cn.hutool.core.io.FileUtil.exist(path)) {
            new File(path).mkdirs();
        }
        return path;
    }

    /**
     * 静态资源访问路径：http://localhost:serverPort+prePath+“/file”：http://localhost:11080/badminton/file
     * /file 配置在securityConfig中
     *
     * @param basePath
     * @return
     */
    public static String getUrlPath(String basePath) {
        return basePath.replace(filePath, "http://localhost:" + serverPort + prePath + "/files");
    }

}
